#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtNetwork import QNetworkAccessManager,  QNetworkRequest,  QNetworkReply
from PyQt5.Qt import QObject,  QUrl,  QApplication,  QVariant
from PyQt5.QtCore import pyqtSignal,  pyqtSlot, QJsonDocument 
import json

class PostMessage(QObject):
    
    onmessage = pyqtSignal(dict)
    
    def __init__(self):
        super(PostMessage,  self).__init__()
        self.netManager = QNetworkAccessManager(self)
        self.netManager.finished.connect(self.replyFinished)
        
    def post(self,  url,  content):
        self.req = QNetworkRequest()
        self.req.setUrl(QUrl(url))
        self.req.setHeader(QNetworkRequest.ContentTypeHeader, "application/x-www-form-urlencoded")
        self.req.setHeader(QNetworkRequest.ContentLengthHeader, len(content))
        self.netManager.post(self.req,  content)
        
    def get(self,  url,  content):
        url = url+content
        req = QNetworkRequest(self)
        req.setUrl(QUrl(url))
        self.netManager.get(req)
        
    def replyFinished(self,  reply):
        if ( reply.error() !=QNetworkReply.NoError ):
            print (reply.errorString())
            #self.onmessage.emit(reply.errorString())
            return 
        message = str(reply.readAll(), 'utf-8')
        message = json.loads(message)
        print (message)
        if message != None:
            self.onmessage.emit(message)
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    pm = PostMessage()
    pm.post("www.baidu.com", "")
    sys.exit(app.exec_())
        
    
